package com.example.demo5;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "WelcomeServlet", value = "/WelcomeServlet")
public class WelcomeServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");

        //获取 cookies
        Cookie[] cookies = request.getCookies();
        // 遍历cookies数组
        String lastAccessTime = "";
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            if ("lastAccess".equals(cookies[i].getName())) {
                // 如果cookie的名称为lastAccess,则获取该cookie的值
                lastAccessTime = cookies[i].getValue();
                break;
            }
        }
        PrintWriter pw = response.getWriter();
        if (!lastAccessTime.isEmpty()) {
            pw.write("登录成功，欢迎你" + lastAccessTime);
        } else {
            pw.write("登录失败");
        }


    }

    public void doPost(HttpServletRequest request,
                       HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
